<template>
  <div class="content">
    <div class="loginArea">
      <div class="loginBox">
        <el-row :gutter="10">
          <el-col :span="14">
            <img src="@/assets/images/loginimg.png" alt="" />
          </el-col>
          <el-col :span="10">
            <div class="loginText">仲易学后台管理系统</div>
            <el-form
              ref="loginForm"
              :model="loginFormByPassword"
              :rules="loginFormRulesByPassword"
              label-width="0px"
              class="login_form"
            >
              <el-form-item prop="username" style="margin-top: 40px">
                <el-input
                  class="inps"
                  placeholder="请输入用户名"
                  v-model="loginFormByPassword.username"
                  @keyup.enter.native="enterKey"
                >
                  <template #prefix>
                    <el-icon class="el-input__icon">
                      <user />
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input
                  class="inps"
                  placeholder="请输入密码"
                  v-model="loginFormByPassword.password"
                  type="password"
                  @keyup.enter.native="enterKey"
                >
                  <template #prefix>
                    <el-icon class="el-input__icon">
                      <lock />
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="captcha">
                <div>
                  <el-input
                    style="width: 150px"
                    class="inps"
                    v-model="loginFormByPassword.captcha"
                    placeholder="输入验证码"
                    @keyup.enter.native="enterKey"
                  >
                  </el-input>
                  <el-image
                    @click="getCaptchaImg()"
                    style="
                      width: 120px;
                      position: absolute;
                      height: 42px;
                      margin-left: 20px;
                    "
                    :src="url"
                  ></el-image>
                </div>
              </el-form-item>
              <el-row>
                <el-col :span="12">
                  <el-checkbox v-model="remeberPassword" class="remember"
                    >记住密码</el-checkbox
                  >
                </el-col>
                <el-col :span="12">
                  <span class="tips">忘记密码？</span>
                </el-col>
              </el-row>
              <el-form-item style="margin-top: 25px; text-align: center">
                <el-button
                  type="primary"
                  @click="loginByPassword"
                  class="submitBtn"
                  >登录</el-button
                >
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
import { useRouter } from "vue-router";
import { reactive, ref, toRefs } from "vue";
import { login, getCaptch } from "@/api/Login/login";
import { getAdmInfo } from "@/api/User/admin";
import { setCookie, getCookie } from "@/utils/cookie";
import { ElMessage } from "element-plus";
export default {
  name: "Login",
  setup() {
    const loginForm = ref(null);
    const router = useRouter();
    const state = reactive({
      url: "",
      // 是否记住密码：
      remeberPassword: false,
      // 密码登录的表单
      loginFormByPassword: {
        username: "",
        password: "",
        captcha: "",
      },
      // 密码登录表单的验证规则对象
      loginFormRulesByPassword: {
        username: [{ required: true, message: "请输入账号", trigger: "blur" }],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "密码长度在6到15个字符",
            trigger: "blur",
          },
        ],
        captcha: [
          { required: true, message: "请输入验证码", trigger: "blur" },
          {
            min: 4,
            max: 4,
            message: "验证码长度为4个字符",
            trigger: "blur",
          },
        ],
      },
    });
    const enterKey = (e) => {
      if (e.keyCode === 13) {
        loginByPassword();
      }
    };
    const getCaptchaImg = async () => {
      state.url = await getCaptch();
    };
    const loginByPassword = () => {
      loginForm.value.validate(async (valid) => {
        if (!valid) {
          return ElMessage.error("当前填写信息有误！");
        }
        state.loginFormByPassword.captcha =
          state.loginFormByPassword.captcha.toLowerCase();
        const { data: res } = await login(state.loginFormByPassword);
        if (res.ret !== 0) {
          getCaptchaImg();
          return ElMessage.error(res.msg);
        }
        // // 1、将登录成功后的token，保存到客户端的 sessionStorage 中
        //  1.1 项目中除了登录的其他API接口，必须在登录后才能访问
        //  1.2 token 只在当前网站打开期间有效，所以将 token 保存在 sessionStoarg 中
        window.sessionStorage.setItem("token", res.token);
        window.sessionStorage.setItem("userId", res.userId + "");
        window.sessionStorage.setItem("permis", JSON.stringify(res.permis));
        const { data: findAdm } = await getAdmInfo(res.userId);
        if (findAdm.ret == 2) {
          getCaptchaImg();
          return ElMessage.error("当前用户非管理员，暂无权限登录");
        }
        // // 如果选择了记住密码，就将用户名和密码存储到cookie中
        if (state.remeberPassword) {
          setCookie(
            state.loginFormByPassword.username,
            state.loginFormByPassword.password,
            7
          );
        }
        ElMessage.success("登录成功！");
        router.push("/");
      });
    };
    // 获取cookie
    const getInfoByCookie = () => {
      const obj = getCookie();
      state.loginFormByPassword.username = obj.username;
      state.loginFormByPassword.password = obj.password;
    };
    const resetForm = () => {
      loginForm.value.resetFields();
    };
    getCaptchaImg();
    getInfoByCookie();
    return {
      ...toRefs(state),
      loginForm,
      enterKey,
      getCaptchaImg,
      loginByPassword,
      getInfoByCookie,
      resetForm,
    };
  },
};
</script>

<style lang="scss" scoped>
.content {
  width: 100vw;
  padding: 0;
  margin: 0;
  height: 100vh;
  font-size: 16px;
  background: url("@/assets/images/loginbg.png");
  background-size: 100%;
  position: relative;
  .title {
    color: white;
    font-size: 45px;
    letter-spacing: 10px;
    position: absolute;
    top: 45px;
    left: 50%;
    transform: translate(-50%, 0);
  }
  .loginArea {
    background-color: rgba(255, 255, 255, 0.8);
    width: 1000px;
    height: 500px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    padding: 80px 50px 50px 40px;
    border-radius: 20px;
    box-shadow: 0px 0px 5px #fff;
  }
  .loginBox {
    .el-input__icon {
      padding: 13px 0;
    }
    .loginText {
      color: #0088ff;
      font-weight: 500;
      text-align: center;
      font-size: 30px;
    }
    :deep(.inps input) {
      color: white;
      background-color: #2a3543;
      font-size: 12px;
      border: none;
      opacity: 0.5;
    }
    .submitBtn {
      background-color: #419eff;
      width: 450px;
      color: #fff;
    }
    .remember,
    .tips {
      font-size: 13px;
      cursor: pointer;
    }
    .tips {
      float: right;
    }
  }
}
</style>
